const Koa = require('koa');

const app = new Koa();

const static = require('koa-static'); //处理静态资源

const views = require('koa-views');//ejs模板

const fs = require('fs');

const path = require('path');

// 加载模板引擎 __dirname:当前js文件所在路径
app.use(views(path.join(__dirname, '../views'), {
    extension: 'ejs'
}))

//koa 中间件 是async await函数  app.use() 去挂载中间件

//process.cwd()  当前进程的目录

app.use(static(process.cwd()))  // /  ---> index.html 

app.use(async (ctx,next) => {
    let url = path.join(process.cwd(),ctx.path);
    if(fs.existsSync(url)){
        //1.判断当前路径是否存在
        if(fs.statSync(url).isDirectory()){
            //2.判断当前路径是文件还是文件夹
            //是文件夹
            let list = fs.readdirSync(url);  //只读一层目录
            let listArr = list.map(item => {
                return path.join(ctx.path,item);
            })

            await ctx.render('index',{
                title:'hello',
                list,
                listArr
            })
        }
    }
})

module.exports = app;

